// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include "conversion.h"
#include <pollux/vector/arrow/abi.h>
#include <pollux/vector/arrow/bridge.h>
#include "context.h"

namespace kumo::pollux::py {
    namespace py = pybind11;

    void addConversionBindings(py::module &m, bool asModuleLocalDefinitions) {
        m.def("export_to_arrow", [](VectorPtr &inputVector) {
            auto arrowArray = std::make_unique<ArrowArray>();
            auto pool_ = PyPolluxContext::getSingletonInstance().pool();
            kumo::pollux::export_to_arrow(inputVector, *arrowArray, pool_);

            auto arrowSchema = std::make_unique<ArrowSchema>();
            kumo::pollux::export_to_arrow(inputVector, *arrowSchema);

            py::module arrow_module = py::module::import("pyarrow");
            py::object array_class = arrow_module.attr("Array");
            return array_class.attr("_import_from_c")(
                reinterpret_cast<uintptr_t>(arrowArray.get()),
                reinterpret_cast<uintptr_t>(arrowSchema.get()));
        });

        m.def("import_from_arrow", [](py::object inputArrowArray) {
            auto arrowArray = std::make_unique<ArrowArray>();
            auto arrowSchema = std::make_unique<ArrowSchema>();
            inputArrowArray.attr("_export_to_c")(
                reinterpret_cast<uintptr_t>(arrowArray.get()),
                reinterpret_cast<uintptr_t>(arrowSchema.get()));
            auto pool_ = PyPolluxContext::getSingletonInstance().pool();
            return import_from_arrow_as_owner(*arrowSchema, *arrowArray, pool_);
        });
    }
} // namespace kumo::pollux::py
